# _*_ coding: utf-8 _*_
"""
Time:     2022/3/9 23:21
Author:   suhong
Version:  V 0.1
File:     public.py
"""
import logging
import os
from os import path
from pathlib import Path
from configparser import ConfigParser
import yaml
import openpyxl as openpyxl

BASE_DIR = Path(__file__).resolve().parent.parent
print(BASE_DIR)

# 基础路径 F:\有妖气TEST
class GetPath():
    def get_path(self, folder_path: str, filename=None):
        '''
        获取路径，如果不存在则创建一个
        :filename:文件名称
        :return:
        '''
        finl_bath = path.join(str(BASE_DIR) + folder_path)
        if not Path(finl_bath).is_dir():
            try:
                os.mkdir(finl_bath)
            except:
                pass
        if filename:
            f_bath = path.join(finl_bath, str(filename))
            if path.isfile(f_bath):
                return f_bath
            '''
            如果不是一个文件则用open的方法创建一个
            '''
            f = open(f_bath, 'a', encoding='utf-8')
            f.close()
            return f_bath
        return finl_bath


class GetIniDate():
    '''
    提取ini文件信息
    '''

    def __init__(self, ini_path=r'\config\config.ini'):
        self.__config = ConfigParser()
        self.__config.read(str(BASE_DIR) + ini_path, encoding='utf-8')

    def get_init_data(self, *args):
        """
        读取ini文件的内容
        :return:
        """
        try:
            return self.__config.get(*args)
        except TypeError:
            raise ValueError("请输入正确的参数")


class GetExcelDate():
    def get_excel_data(self, file, sheet_name):

        '''
        读取.xlsx文件
        :param file:文件地址
        :param sheet:文件表尾名
        :return:
        '''
        wb = openpyxl.load_workbook(file)
        sheet = wb[sheet_name]
        one_line_data_list = []
        all_line_data_list = []
        one_line_tuple = ()
        status = True
        for one_line_data_tuple in sheet:
            if status:
                '''
                不打印第一行
                '''
                status = False
                continue
            # print(i)
            for one_data_cell in one_line_data_tuple:
                # print(a.value)
                if one_data_cell:
                    if one_data_cell.value == '':
                        one_data_cell.value = None
                one_line_data_list.append(one_data_cell.value)
            # print(one_line_data_list)
            if one_line_data_list[0] == None:
                # 第一列index为空不输出
                continue
            one_line_tuple = tuple(one_line_data_list)
            all_line_data_list.append(one_line_tuple)
            # print(one_line_tuple)
            one_line_data_list.clear()
        return all_line_data_list
        print(all_line_data_list)


class GetYmalData:
    def get_ymal_data(self, file):
        '''
        读取ymal文件的内容
        :return:
        '''
        with open(file, mode='r', encoding='utf-8') as yaml_file:
            yaml_data = yaml_file.read()
        # 转换成字典
        return yaml.safe_load(yaml_data)


class GetLogger:
    '''
    封装日志
    '''

    def __init__(self, log_path):
        self.file_name = log_path
        self.login = logging.getLogger()
        self.login.setLevel(logging.DEBUG)
        self.formatter = logging.Formatter('[%(asctime)s] - [%(filename)s] - [%(levelname)s] : %(message)s')

    def _console(self, level, msg):
        # 创建FileHandler对象,把日志写入文件，a表示追加
        fh = logging.FileHandler(self.file_name, mode="a", encoding="utf-8")
        # 日志等级
        # fh.setLevel(logging.DEBUG)
        # 日志格式
        fh.setFormatter(self.formatter)
        # 添加内容到文件
        self.login.addHandler(fh)
        if level == "info":
            self.login.info(msg)
        elif level == "debug":
            self.login.debug(msg)
        elif level == "warning":
            self.login.warning(msg)
        elif level == "error":
            self.login.error(msg)
        self.login.removeHandler(fh)
        fh.close()

    def info(self, msg):
        self._console("info", msg)

    def debug(self, msg):
        self._console("debug", msg)

    def warning(self, msg):
        self._console("warning", msg)

    def error(self, msg):
        self._console("error", msg)


if __name__ == '__main__':
    # GetPath().get_path('/Lib','123.txt')
    # res=GetIniDate().get_init_data("URL","ProjectURl")
    # print(res)
    # c = GetPath().get_path(r'\datas', 'loging.xlsx')
    # GetExcelDate().get_excel_data(c, "loging_success")
    # l=GetPath().get_path('\elements','login_page.yaml')
    # print(l)
    # d=GetYmalData().get_ymal_data(l)
    # print(d["头像"])
    a=GetLogger(r"F:\有妖气TEST\results\logger\logger.txt")
    a.debug("这是一个测试")